#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
综合过滤与分析测试套件

本模块提供完整的测试框架，涵盖从信号过滤到状态分析的全流程测试，
包括过滤器性能评估、状态转换检测准确性、异常处理能力等。

作者: 脑波分析系统开发团队
创建时间: 2025年1月
版本: 1.0.0
"""

import sys
import os
import numpy as np
import json
import time
from datetime import datetime
from typing import Dict, List, Tuple, Any, Optional
from dataclasses import dataclass
from pathlib import Path


class NumpyEncoder(json.JSONEncoder):
    """自定义JSON编码器，处理numpy类型"""
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, np.bool_):
            return bool(obj)
        return super(NumpyEncoder, self).default(obj)

# 添加项目根目录到路径
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, project_root)

# 导入项目模块
try:
    from service.AdvancedSignalFilter import AdvancedSignalFilter
except ImportError as e:
    print(f"无法导入AdvancedSignalFilter: {e}")
    print(f"项目根目录: {project_root}")
    print(f"当前工作目录: {os.getcwd()}")
    print(f"Python路径: {sys.path[:3]}")
    # 尝试直接导入
    service_path = os.path.join(project_root, 'service')
    if os.path.exists(service_path):
        print(f"Service目录存在: {service_path}")
        sys.path.insert(0, service_path)
        from AdvancedSignalFilter import AdvancedSignalFilter
    else:
        print(f"Service目录不存在: {service_path}")
        raise

from biologically_realistic_data import BiologicallyRealisticDataGenerator


@dataclass
class TestResult:
    """
    测试结果数据类
    """
    test_name: str
    test_type: str
    passed: bool
    execution_time: float
    details: Dict[str, Any]
    error_message: Optional[str] = None
    warnings: List[str] = None
    
    def __post_init__(self):
        if self.warnings is None:
            self.warnings = []


@dataclass
class FilterPerformanceMetrics:
    """
    过滤器性能指标
    """
    anomaly_detection_rate: float
    false_positive_rate: float
    processing_time_per_second: float
    memory_usage_mb: float
    filter_effectiveness: float
    state_transition_accuracy: float


class ComprehensiveTestSuite:
    """
    综合测试套件
    
    提供完整的过滤器和分析算法测试功能，
    包括性能测试、准确性测试、鲁棒性测试等。
    """
    
    def __init__(self, test_data_path: str = None):
        """
        初始化测试套件
        
        Args:
            test_data_path: 测试数据文件路径
        """
        self.test_results: List[TestResult] = []
        self.data_generator = BiologicallyRealisticDataGenerator()
        self.filter = AdvancedSignalFilter()
        
        # 加载测试数据
        if test_data_path and os.path.exists(test_data_path):
            with open(test_data_path, 'r', encoding='utf-8') as f:
                self.test_data = json.load(f)
        else:
            print("生成新的测试数据...")
            self.test_data = self.data_generator.generate_comprehensive_test_dataset()
        
        # 测试配置
        self.test_config = {
            'tolerance_threshold': 0.1,  # 容忍阈值
            'performance_threshold': 1.0,  # 性能阈值（秒/秒）
            'memory_threshold': 100.0,  # 内存阈值（MB）
            'accuracy_threshold': 0.85,  # 准确率阈值
            'max_anomaly_rate': 0.05  # 最大异常率
        }
    
    def test_long_term_stable_states(self) -> List[TestResult]:
        """
        测试长期稳定状态的过滤效果
        
        Returns:
            测试结果列表
        """
        results = []
        
        for i, stable_data in enumerate(self.test_data['long_term_stable_states']):
            test_name = f"长期稳定状态测试_{i+1}_{stable_data['state']}"
            start_time = time.time()
            
            try:
                # 转换信号数据
                signal = np.array(stable_data['signal'])
                expected_state = stable_data['expected_classification']
                
                # 将时间序列信号转换为波段功率值字典
                band_powers = self._extract_band_powers(signal, stable_data['sampling_rate'])
                
                # 应用过滤器
                filter_result = self.filter.process_multi_band_signal_dict(band_powers)
                
                # 分析过滤结果
                anomaly_flags = filter_result.get('anomaly_flags', {})
                anomaly_count = sum(1 for flag in anomaly_flags.values() if flag)
                total_bands = len(anomaly_flags)
                anomaly_rate = anomaly_count / max(total_bands, 1)
                
                # 评估测试结果
                passed = anomaly_rate <= self.test_config['max_anomaly_rate']
                
                execution_time = time.time() - start_time
                
                result = TestResult(
                    test_name=test_name,
                    test_type="long_term_stable",
                    passed=passed,
                    execution_time=execution_time,
                    details={
                        'expected_state': expected_state,
                        'signal_length': len(signal),
                        'duration_minutes': stable_data['duration_minutes'],
                        'anomaly_count': anomaly_count,
                        'anomaly_rate': anomaly_rate,
                        'band_powers': band_powers,
                        'filter_result': filter_result,
                        'signal_quality': self._assess_signal_quality(signal)
                    }
                )
                
                if not passed:
                    result.warnings.append(f"异常率过高: {anomaly_rate:.3f} > {self.test_config['max_anomaly_rate']}")
                
                results.append(result)
                
            except Exception as e:
                result = TestResult(
                    test_name=test_name,
                    test_type="long_term_stable",
                    passed=False,
                    execution_time=time.time() - start_time,
                    details={},
                    error_message=str(e)
                )
                results.append(result)
        
        return results
    
    def test_state_transition_cycles(self) -> List[TestResult]:
        """
        测试状态转换周期的过滤效果
        
        Returns:
            测试结果列表
        """
        results = []
        
        for i, cycle_data in enumerate(self.test_data['state_transition_cycles']):
            test_name = f"状态转换周期测试_{i+1}_{cycle_data['test_type']}"
            start_time = time.time()
            
            try:
                # 转换信号数据
                signal = np.array(cycle_data['signal'])
                state_timeline = cycle_data['state_timeline']
                
                # 将时间序列信号转换为波段功率值字典
                band_powers = self._extract_band_powers(signal, cycle_data['sampling_rate'])
                
                # 应用过滤器
                filter_result = self.filter.process_multi_band_signal_dict(band_powers)
                
                # 从过滤结果中重构信号用于分析
                filtered_signal = self._reconstruct_signal_from_bands(
                    filter_result['filtered_signals'], len(signal), cycle_data['sampling_rate']
                )
                
                # 分析状态转换期间的过滤效果
                transition_analysis = self._analyze_transition_filtering(
                    signal, filtered_signal, state_timeline, cycle_data['sampling_rate']
                )
                
                # 评估测试结果
                passed = (
                    transition_analysis['transition_anomaly_reduction'] > 0.5 and
                    transition_analysis['stable_state_preservation'] > 0.9
                )
                
                execution_time = time.time() - start_time
                
                result = TestResult(
                    test_name=test_name,
                    test_type="state_transition",
                    passed=passed,
                    execution_time=execution_time,
                    details={
                        'cycle_type': cycle_data['test_type'],
                        'total_duration': cycle_data['total_duration'],
                        'state_count': len([s for s in state_timeline if not s['state'].startswith('transition')]),
                        'transition_count': len([s for s in state_timeline if s['state'].startswith('transition')]),
                        'transition_analysis': transition_analysis,
                        'band_powers': band_powers,
                        'filter_result': filter_result
                    }
                )
                
                if not passed:
                    if transition_analysis['transition_anomaly_reduction'] <= 0.5:
                        result.warnings.append("状态转换期间异常减少不足")
                    if transition_analysis['stable_state_preservation'] <= 0.9:
                        result.warnings.append("稳定状态保持度不足")
                
                results.append(result)
                
            except Exception as e:
                result = TestResult(
                    test_name=test_name,
                    test_type="state_transition",
                    passed=False,
                    execution_time=time.time() - start_time,
                    details={},
                    error_message=str(e)
                )
                results.append(result)
        
        return results
    
    def test_edge_cases(self) -> List[TestResult]:
        """
        测试边缘状态的处理能力
        
        Returns:
            测试结果列表
        """
        results = []
        
        for i, edge_data in enumerate(self.test_data['edge_cases']):
            test_name = f"边缘状态测试_{i+1}_{edge_data['edge_type']}"
            start_time = time.time()
            
            try:
                # 转换信号数据
                signal = np.array(edge_data['signal'])
                
                # 将时间序列信号转换为波段功率值字典
                band_powers = self._extract_band_powers(signal, self.data_generator.sampling_rate)
                
                # 应用过滤器
                filter_result = self.filter.process_multi_band_signal_dict(band_powers)
                
                # 从过滤结果中重构信号用于分析
                filtered_signal = self._reconstruct_signal_from_bands(
                    filter_result['filtered_signals'], len(signal), self.data_generator.sampling_rate
                )
                
                # 分析边缘状态处理效果
                edge_analysis = self._analyze_edge_case_handling(
                    signal, filtered_signal, filter_result
                )
                
                # 评估测试结果（边缘状态允许更高的容忍度）
                passed = (
                    edge_analysis['signal_preservation'] > 0.8 and
                    edge_analysis['anomaly_rate'] < 0.15
                )
                
                execution_time = time.time() - start_time
                
                result = TestResult(
                    test_name=test_name,
                    test_type="edge_case",
                    passed=passed,
                    execution_time=execution_time,
                    details={
                        'edge_type': edge_data['edge_type'],
                        'expected_classifications': edge_data['expected_classification'],
                        'edge_analysis': edge_analysis,
                        'filter_result': filter_result
                    }
                )
                
                if not passed:
                    if edge_analysis['signal_preservation'] <= 0.8:
                        result.warnings.append("信号保持度不足")
                    if edge_analysis['anomaly_rate'] >= 0.15:
                        result.warnings.append("异常率过高")
                
                results.append(result)
                
            except Exception as e:
                result = TestResult(
                    test_name=test_name,
                    test_type="edge_case",
                    passed=False,
                    execution_time=time.time() - start_time,
                    details={},
                    error_message=str(e)
                )
                results.append(result)
        
        return results
    
    def test_extreme_cases(self) -> List[TestResult]:
        """
        测试极端状态的鲁棒性
        
        Returns:
            测试结果列表
        """
        results = []
        
        for i, extreme_data in enumerate(self.test_data['extreme_cases']):
            test_name = f"极端状态测试_{i+1}_{extreme_data['extreme_type']}"
            start_time = time.time()
            
            try:
                # 转换信号数据
                signal = np.array(extreme_data['signal'])
                
                # 将时间序列信号转换为波段功率值字典
                band_powers = self._extract_band_powers(signal, self.data_generator.sampling_rate)
                
                # 应用过滤器
                filter_result = self.filter.process_multi_band_signal_dict(band_powers)
                
                # 从过滤结果中重构信号用于分析
                filtered_signal = self._reconstruct_signal_from_bands(
                    filter_result['filtered_signals'], len(signal), self.data_generator.sampling_rate
                )
                
                # 分析极端状态处理效果
                extreme_analysis = self._analyze_extreme_case_handling(
                    signal, filtered_signal, filter_result
                )
                
                # 评估测试结果（极端状态重点关注稳定性）
                passed = (
                    extreme_analysis['processing_stability'] > 0.9 and
                    extreme_analysis['no_critical_errors']
                )
                
                execution_time = time.time() - start_time
                
                result = TestResult(
                    test_name=test_name,
                    test_type="extreme_case",
                    passed=passed,
                    execution_time=execution_time,
                    details={
                        'extreme_type': extreme_data['extreme_type'],
                        'expected_classification': extreme_data['expected_classification'],
                        'extreme_analysis': extreme_analysis,
                        'filter_result': filter_result
                    }
                )
                
                if not passed:
                    if extreme_analysis['processing_stability'] <= 0.9:
                        result.warnings.append("处理稳定性不足")
                    if not extreme_analysis['no_critical_errors']:
                        result.warnings.append("存在严重错误")
                
                results.append(result)
                
            except Exception as e:
                result = TestResult(
                    test_name=test_name,
                    test_type="extreme_case",
                    passed=False,
                    execution_time=time.time() - start_time,
                    details={},
                    error_message=str(e)
                )
                results.append(result)
        
        return results
    
    def test_performance_benchmarks(self) -> List[TestResult]:
        """
        测试性能基准
        
        Returns:
            测试结果列表
        """
        results = []
        
        # 生成不同长度的测试信号
        test_durations = [60, 300, 1800, 3600]  # 1分钟、5分钟、30分钟、1小时
        
        for duration in test_durations:
            test_name = f"性能基准测试_{duration}秒"
            start_time = time.time()
            
            try:
                # 生成测试信号
                signal = self.data_generator.generate_signal_for_state('awake', duration)
                
                # 测量内存使用（简化版）
                import psutil
                process = psutil.Process()
                memory_before = process.memory_info().rss / 1024 / 1024  # MB
                
                # 将时间序列信号转换为波段功率值字典
                band_powers = self._extract_band_powers(signal, self.data_generator.sampling_rate)
                
                # 应用过滤器
                filter_start = time.time()
                filter_result = self.filter.process_multi_band_signal_dict(band_powers)
                
                # 从过滤结果中重构信号用于分析
                filtered_signal = self._reconstruct_signal_from_bands(
                    filter_result['filtered_signals'], len(signal), self.data_generator.sampling_rate
                )
                filter_time = time.time() - filter_start
                
                memory_after = process.memory_info().rss / 1024 / 1024  # MB
                memory_usage = memory_after - memory_before
                
                # 计算性能指标
                processing_rate = duration / filter_time  # 实时倍数
                
                # 评估测试结果
                passed = (
                    processing_rate >= self.test_config['performance_threshold'] and
                    memory_usage <= self.test_config['memory_threshold']
                )
                
                execution_time = time.time() - start_time
                
                result = TestResult(
                    test_name=test_name,
                    test_type="performance",
                    passed=passed,
                    execution_time=execution_time,
                    details={
                        'signal_duration': duration,
                        'signal_length': len(signal),
                        'filter_time': filter_time,
                        'processing_rate': processing_rate,
                        'memory_usage_mb': memory_usage,
                        'filter_result': filter_result
                    }
                )
                
                if not passed:
                    if processing_rate < self.test_config['performance_threshold']:
                        result.warnings.append(f"处理速度不足: {processing_rate:.2f}x < {self.test_config['performance_threshold']}x")
                    if memory_usage > self.test_config['memory_threshold']:
                        result.warnings.append(f"内存使用过高: {memory_usage:.1f}MB > {self.test_config['memory_threshold']}MB")
                
                results.append(result)
                
            except Exception as e:
                result = TestResult(
                    test_name=test_name,
                    test_type="performance",
                    passed=False,
                    execution_time=time.time() - start_time,
                    details={},
                    error_message=str(e)
                )
                results.append(result)
        
        return results
    
    def _extract_band_powers(self, signal: np.ndarray, sampling_rate: int) -> Dict[str, int]:
        """
        从时间序列信号中提取各频段功率值
        
        Args:
            signal: 时间序列信号数组
            sampling_rate: 采样率
            
        Returns:
            各频段功率值字典
        """
        from scipy import signal as scipy_signal
        
        # 计算功率谱密度
        freqs, psd = scipy_signal.welch(signal, fs=sampling_rate, nperseg=min(len(signal)//4, 1024))
        
        # 定义频段范围
        bands = {
            'delta': (0.5, 4),
            'theta': (4, 8),
            'low_alpha': (8, 10),
            'high_alpha': (10, 13),
            'low_beta': (13, 20),
            'high_beta': (20, 30),
            'low_gamma': (30, 40),
            'high_gamma': (40, 50)
        }
        
        # 计算各频段功率
        band_powers = {}
        for band_name, (low_freq, high_freq) in bands.items():
            # 找到频段范围内的索引
            band_mask = (freqs >= low_freq) & (freqs <= high_freq)
            if np.any(band_mask):
                # 计算频段内的平均功率并转换为整数
                power = np.mean(psd[band_mask]) * 1000000  # 放大以获得合理的整数值
                band_powers[band_name] = int(power)
            else:
                band_powers[band_name] = 1000  # 默认值
        
        return band_powers
    
    def _reconstruct_signal_from_bands(self, band_powers: Dict[str, int], signal_length: int, sampling_rate: int) -> np.ndarray:
        """
        从频段功率值重构时间序列信号（用于分析目的）
        
        Args:
            band_powers: 频段功率值字典
            signal_length: 目标信号长度
            sampling_rate: 采样率
            
        Returns:
            重构的时间序列信号
        """
        # 简化的信号重构：基于功率值生成合成信号
        t = np.linspace(0, signal_length / sampling_rate, signal_length)
        reconstructed_signal = np.zeros(signal_length)
        
        # 定义频段中心频率
        band_freqs = {
            'delta': 2.25,
            'theta': 6,
            'low_alpha': 9,
            'high_alpha': 11.5,
            'low_beta': 16.5,
            'high_beta': 25,
            'low_gamma': 35,
            'high_gamma': 45
        }
        
        # 为每个频段生成正弦波并按功率加权
        for band_name, power in band_powers.items():
            if band_name in band_freqs:
                freq = band_freqs[band_name]
                amplitude = np.sqrt(power / 1000000)  # 反向缩放
                reconstructed_signal += amplitude * np.sin(2 * np.pi * freq * t)
        
        return reconstructed_signal
    
    def _assess_signal_quality(self, signal: np.ndarray) -> Dict[str, float]:
        """
        评估信号质量
        
        Args:
            signal: 信号数组
            
        Returns:
            信号质量指标字典
        """
        return {
            'snr_db': self._calculate_snr(signal),
            'stability': self._calculate_stability(signal),
            'continuity': self._calculate_continuity(signal)
        }
    
    def _calculate_snr(self, signal: np.ndarray) -> float:
        """
        计算信噪比
        
        Args:
            signal: 信号数组
            
        Returns:
            信噪比（dB）
        """
        # 简化的SNR计算
        signal_power = np.mean(signal ** 2)
        noise_power = np.var(np.diff(signal))  # 使用差分估计噪声
        
        if noise_power > 0:
            snr = 10 * np.log10(signal_power / noise_power)
        else:
            snr = float('inf')
        
        return snr
    
    def _calculate_stability(self, signal: np.ndarray) -> float:
        """
        计算信号稳定性
        
        Args:
            signal: 信号数组
            
        Returns:
            稳定性指标（0-1）
        """
        # 使用滑动窗口计算方差的变化
        window_size = min(1000, len(signal) // 10)
        if window_size < 10:
            return 1.0
        
        variances = []
        for i in range(0, len(signal) - window_size, window_size // 2):
            window = signal[i:i + window_size]
            variances.append(np.var(window))
        
        if len(variances) < 2:
            return 1.0
        
        stability = 1.0 - (np.std(variances) / (np.mean(variances) + 1e-10))
        return max(0.0, min(1.0, stability))
    
    def _calculate_continuity(self, signal: np.ndarray) -> float:
        """
        计算信号连续性
        
        Args:
            signal: 信号数组
            
        Returns:
            连续性指标（0-1）
        """
        # 检测突变点
        diff = np.abs(np.diff(signal))
        threshold = np.percentile(diff, 95)  # 95%分位数作为阈值
        
        sudden_changes = np.sum(diff > threshold)
        continuity = 1.0 - (sudden_changes / len(signal))
        
        return max(0.0, min(1.0, continuity))
    
    def _analyze_transition_filtering(
        self, 
        original_signal: np.ndarray, 
        filtered_signal: np.ndarray, 
        state_timeline: List[Dict], 
        sampling_rate: int
    ) -> Dict[str, float]:
        """
        分析状态转换期间的过滤效果
        
        Args:
            original_signal: 原始信号
            filtered_signal: 过滤后信号
            state_timeline: 状态时间线
            sampling_rate: 采样率
            
        Returns:
            转换分析结果
        """
        transition_periods = [s for s in state_timeline if s['state'].startswith('transition')]
        stable_periods = [s for s in state_timeline if not s['state'].startswith('transition')]
        
        transition_anomaly_reduction = 0.0
        stable_state_preservation = 0.0
        
        if transition_periods:
            # 分析转换期间的异常减少
            transition_anomalies_before = 0
            transition_anomalies_after = 0
            
            for period in transition_periods:
                start_idx = int(period['start_time'] * sampling_rate)
                end_idx = int(period['end_time'] * sampling_rate)
                
                if end_idx <= len(original_signal):
                    orig_segment = original_signal[start_idx:end_idx]
                    filt_segment = filtered_signal[start_idx:end_idx]
                    
                    # 简化的异常检测
                    orig_anomalies = np.sum(np.abs(np.diff(orig_segment)) > np.std(orig_segment) * 3)
                    filt_anomalies = np.sum(np.abs(np.diff(filt_segment)) > np.std(filt_segment) * 3)
                    
                    transition_anomalies_before += orig_anomalies
                    transition_anomalies_after += filt_anomalies
            
            if transition_anomalies_before > 0:
                transition_anomaly_reduction = 1.0 - (transition_anomalies_after / transition_anomalies_before)
            else:
                transition_anomaly_reduction = 1.0
        
        if stable_periods:
            # 分析稳定期间的信号保持
            preservation_scores = []
            
            for period in stable_periods:
                start_idx = int(period['start_time'] * sampling_rate)
                end_idx = int(period['end_time'] * sampling_rate)
                
                if end_idx <= len(original_signal):
                    orig_segment = original_signal[start_idx:end_idx]
                    filt_segment = filtered_signal[start_idx:end_idx]
                    
                    # 计算相关性作为保持度指标
                    if len(orig_segment) > 1 and np.std(orig_segment) > 0 and np.std(filt_segment) > 0:
                        correlation = np.corrcoef(orig_segment, filt_segment)[0, 1]
                        preservation_scores.append(max(0, correlation))
            
            if preservation_scores:
                stable_state_preservation = np.mean(preservation_scores)
        
        return {
            'transition_anomaly_reduction': transition_anomaly_reduction,
            'stable_state_preservation': stable_state_preservation,
            'transition_count': len(transition_periods),
            'stable_count': len(stable_periods)
        }
    
    def _analyze_edge_case_handling(
        self, 
        original_signal: np.ndarray, 
        filtered_signal: np.ndarray, 
        filter_info: Dict
    ) -> Dict[str, float]:
        """
        分析边缘状态处理效果
        
        Args:
            original_signal: 原始信号
            filtered_signal: 过滤后信号
            filter_info: 过滤器信息
            
        Returns:
            边缘状态分析结果
        """
        # 计算信号保持度
        if len(original_signal) > 1 and np.std(original_signal) > 0 and np.std(filtered_signal) > 0:
            signal_preservation = max(0, np.corrcoef(original_signal, filtered_signal)[0, 1])
        else:
            signal_preservation = 0.0
        
        # 计算异常率
        anomaly_count = len(filter_info.get('anomalies', []))
        total_segments = len(original_signal) // 1000  # 假设每1000个样本为一段
        anomaly_rate = anomaly_count / max(total_segments, 1)
        
        return {
            'signal_preservation': signal_preservation,
            'anomaly_rate': anomaly_rate,
            'anomaly_count': anomaly_count
        }
    
    def _analyze_extreme_case_handling(
        self, 
        original_signal: np.ndarray, 
        filtered_signal: np.ndarray, 
        filter_info: Dict
    ) -> Dict[str, Any]:
        """
        分析极端状态处理效果
        
        Args:
            original_signal: 原始信号
            filtered_signal: 过滤后信号
            filter_info: 过滤器信息
            
        Returns:
            极端状态分析结果
        """
        # 检查处理稳定性
        processing_stability = 1.0
        if np.any(np.isnan(filtered_signal)) or np.any(np.isinf(filtered_signal)):
            processing_stability = 0.0
        elif np.std(filtered_signal) == 0:
            processing_stability = 0.5  # 信号被过度平滑
        
        # 检查是否有严重错误
        no_critical_errors = True
        if 'errors' in filter_info and filter_info['errors']:
            critical_errors = [e for e in filter_info['errors'] if 'critical' in str(e).lower()]
            no_critical_errors = len(critical_errors) == 0
        
        return {
            'processing_stability': processing_stability,
            'no_critical_errors': no_critical_errors,
            'signal_range': np.ptp(filtered_signal),
            'signal_mean': np.mean(filtered_signal),
            'signal_std': np.std(filtered_signal)
        }
    
    def run_all_tests(self) -> Dict[str, Any]:
        """
        运行所有测试
        
        Returns:
            完整的测试结果
        """
        print("开始运行综合测试套件...")
        start_time = time.time()
        
        # 运行各类测试
        print("\n1. 运行长期稳定状态测试...")
        stable_results = self.test_long_term_stable_states()
        self.test_results.extend(stable_results)
        
        print("2. 运行状态转换周期测试...")
        transition_results = self.test_state_transition_cycles()
        self.test_results.extend(transition_results)
        
        print("3. 运行边缘状态测试...")
        edge_results = self.test_edge_cases()
        self.test_results.extend(edge_results)
        
        print("4. 运行极端状态测试...")
        extreme_results = self.test_extreme_cases()
        self.test_results.extend(extreme_results)
        
        print("5. 运行性能基准测试...")
        performance_results = self.test_performance_benchmarks()
        self.test_results.extend(performance_results)
        
        total_time = time.time() - start_time
        
        # 生成测试报告
        report = self._generate_test_report(total_time)
        
        print(f"\n测试完成！总耗时: {total_time:.2f}秒")
        return report
    
    def _generate_test_report(self, total_time: float) -> Dict[str, Any]:
        """
        生成测试报告
        
        Args:
            total_time: 总测试时间
            
        Returns:
            测试报告字典
        """
        # 统计测试结果
        total_tests = len(self.test_results)
        passed_tests = sum(1 for r in self.test_results if r.passed)
        failed_tests = total_tests - passed_tests
        
        # 按测试类型分组统计
        type_stats = {}
        for result in self.test_results:
            test_type = result.test_type
            if test_type not in type_stats:
                type_stats[test_type] = {'total': 0, 'passed': 0, 'failed': 0}
            
            type_stats[test_type]['total'] += 1
            if result.passed:
                type_stats[test_type]['passed'] += 1
            else:
                type_stats[test_type]['failed'] += 1
        
        # 收集警告和错误
        warnings = []
        errors = []
        
        for result in self.test_results:
            if result.warnings:
                warnings.extend([(result.test_name, w) for w in result.warnings])
            if result.error_message:
                errors.append((result.test_name, result.error_message))
        
        # 生成报告
        report = {
            'summary': {
                'total_tests': total_tests,
                'passed_tests': passed_tests,
                'failed_tests': failed_tests,
                'success_rate': passed_tests / total_tests if total_tests > 0 else 0,
                'total_execution_time': total_time,
                'average_test_time': total_time / total_tests if total_tests > 0 else 0
            },
            'type_statistics': type_stats,
            'warnings': warnings,
            'errors': errors,
            'detailed_results': [
                {
                    'test_name': r.test_name,
                    'test_type': r.test_type,
                    'passed': r.passed,
                    'execution_time': r.execution_time,
                    'details': r.details,
                    'warnings': r.warnings,
                    'error_message': r.error_message
                }
                for r in self.test_results
            ],
            'generation_time': datetime.now().isoformat(),
            'test_config': self.test_config
        }
        
        return report
    
    def save_test_report(self, report: Dict[str, Any], filename: str = None) -> str:
        """
        保存测试报告
        
        Args:
            report: 测试报告
            filename: 文件名
            
        Returns:
            保存的文件路径
        """
        if filename is None:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f'comprehensive_test_report_{timestamp}.json'
        
        filepath = os.path.join(
            os.path.dirname(__file__), 
            filename
        )
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(report, f, indent=2, ensure_ascii=False, cls=NumpyEncoder)
        
        return filepath


if __name__ == '__main__':
    # 运行综合测试
    test_suite = ComprehensiveTestSuite()
    
    # 运行所有测试
    report = test_suite.run_all_tests()
    
    # 保存测试报告
    report_path = test_suite.save_test_report(report)
    print(f"\n测试报告已保存到: {report_path}")
    
    # 打印简要结果
    print("\n=== 测试结果摘要 ===")
    print(f"总测试数: {report['summary']['total_tests']}")
    print(f"通过测试: {report['summary']['passed_tests']}")
    print(f"失败测试: {report['summary']['failed_tests']}")
    print(f"成功率: {report['summary']['success_rate']:.1%}")
    print(f"总耗时: {report['summary']['total_execution_time']:.2f}秒")
    
    if report['warnings']:
        print(f"\n警告数: {len(report['warnings'])}")
    
    if report['errors']:
        print(f"错误数: {len(report['errors'])}")
        print("\n错误详情:")
        for test_name, error in report['errors'][:5]:  # 只显示前5个错误
            print(f"  - {test_name}: {error}")